package com.graduate.examapp.viewmodel

import android.content.SharedPreferences
import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.GsonUtils
import com.graduate.examapp.entity.LoginData
import com.graduate.examapp.entity.LoginParam
import com.graduate.examapp.model.LoginRepository
import com.graduate.examapp.request.Response
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

/**
 * Author: etacao
 * Date: 2023/4/11 13:42
 * Description:
 * History:
 * <author> <time> <version> <desc>
 * etacao 2023/4/11 1.0 首次创建
 */
class LoginViewModel : ViewModel() {
    val isLoginSuccess: MutableLiveData<Response<LoginData>> = MutableLiveData()

    private val loginRepository: LoginRepository = LoginRepository()

    fun login(id: String, password: String, sharedPreferences: SharedPreferences) {
        viewModelScope.launch(Dispatchers.IO) {
            Log.d("LoginViewModel", Thread.currentThread().name)
            val loginParam = LoginParam(id, password)
            val response = loginRepository.login(loginParam)
            if (response.code == REQUEST_OK) {
                val userInfoJson = GsonUtils.toJson(response.data)
                response.data.apply {
                    sharedPreferences.edit().also {
                        it.putLong("login_time", System.currentTimeMillis())
                        it.putString(
                            "jwt", this.jwt,
                        )
                        it.putString("user_info", userInfoJson)
                        it.apply()
                    }
                }
            }
            isLoginSuccess.postValue(response)
        }
    }
    companion object {
        const val REQUEST_OK = 200
    }
}
